import * as XLSX from 'xlsx'

// excel 文件解析成json
export const excelToJson = (file: File) => {
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader()
      reader.onload = (e: ProgressEvent<FileReader>) => {
        const data = new Uint8Array(e.target?.result as ArrayBuffer)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet, {
          defval: ''
        })
        resolve(jsonData)
      }
      reader.readAsArrayBuffer(file)
    } catch (error) {
      reject(error)
    }
  })
}

// json 转 excel
export const jsonToExcel = (json: any, fileName = 'excel') => {
  const ws = XLSX.utils.json_to_sheet(json)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, `${fileName}.xlsx`)
}
